<?php
session_start();
require_once '../../database/config.php';
class user
{
    /**
     * 获取用户列表信息（分页提取）
     * param: pageIndex（当前页码）
     * param: pageSize（每页记录数）
     * param：username（查询条件用户名）
     * param：usersex（查询条件性别）
     * param：usertel（查询条件联系电话）
     */
    function getUserListByPage($pageIndex,$pageSize, $username,$usersex, $usertel)
    {
        $sql = "select id,username,usersex,userbirth,useremail,usercard,usertel,registerdate,userstatus,
                case userstatus when 1 then '使用中' when 0 then '停用中' end as statustext from user where 1=1 ";
        if ($username != "") {
            $sql = $sql . " and username like '%$username%'";
        }
        if ($usersex != "") {
            $sql = $sql . " and usersex = '$usersex'";
        }
        if ($usertel != "") {
            $sql = $sql . " and usertel like '%$usertel%'";
        }
        $count = $this ->getUserListCount($sql);
        $startno = ($pageIndex - 1) * $pageSize;
        $sql = $sql . " order by registerdate desc limit $startno," . $pageSize;
        $result = $GLOBALS['conn']->query($sql);
        $result->setFetchMode(PDO::FETCH_ASSOC);
        $userList = array();
        while ($row = $result->fetch()) {
            $userList[] = $row;
        }
        $result = array(
            "code" => 0,
            "count" => $count,
//            "msg" => "success",
            "list" => $userList
        );
        echo json_encode($result);
    }
    /**
     * 获取记录总数（用于实现分页查询）
     * param: sql（查询语句）
     */
    function getUserListCount($sql)
    {
        $result = $GLOBALS['conn']->query($sql);
        return $result->rowCount();
    }
    /**
     * 用户重置密码
     * param：id（记录id）
     */
    function resetPassword($id)
    {
        $sql = "update user set userpwd='" . md5("123456") . "' where id=$id";
        $GLOBALS['conn']->exec($sql);
        $result = array("msg" => "操作成功");
        echo json_encode($result);
    }
    /**
     * 修改用户状态（启用或停用用户）
     * param：id（记录id）
     * param：userstatus（用户状态 0:停用 1：启用）
     */
    function modifyStatus($id, $userstatus)
    {
        if ($userstatus == 1){
            $userstatus = 0;
            $userstatustext = '停用中';
        }else{
            $userstatus = 1;
            $userstatustext = '使用中';
        }
        $sql = "update user set userstatus=$userstatus where id=$id";
        $GLOBALS['conn']->exec($sql);
        $result = array("msg" => "操作成功", "userstatus" => $userstatus, "userstatustext" => $userstatustext);
        echo json_encode($result);
    }
    /**
     * 用户注册
     */
    function addUser()
    {

    }
    /**
     * 用户信息修改
     */
    function modifyUser()
    {

    }
    /**
     * 后台登录（管理员用户登录）
     * param：username（用户名）
     * param：userpwd（密码）
     * param：verifyCode（验证码）
     */
    function adminLogin($usertel, $userpwd, $verifyCode)
    {
        if ($verifyCode != $_SESSION["auth"]) {
            $result = array("msg" => "验证码不正确", "errorCode" => 1);
            echo json_encode($result);
        } else {
            $stmt = $GLOBALS['conn']->prepare("select * from admin where usertel=:usertel and userpwd=:userpwd");
            $stmt->bindParam("usertel",$usertel);
            $stmt->bindParam("userpwd",$userpwd);
            $stmt->execute();
            $stmt->setFetchMode(PDO::FETCH_ASSOC);
            if ($rows = $stmt->fetch()){
                $_SESSION["username"] = $rows["username"];
                $_SESSION["userpwd"] = $rows["userpwd"];
                $_SESSION["userid"] = $rows["id"];
                $_SESSION['MySQL_VERSION'] = $this ->getMysqlVersion();
                $result = array("msg" => "登陆成功", "errorCode" => 0);
                echo json_encode($result);
            }
            else {
                $result = array("msg" => "用户名或密码错误", "errorCode" => 2);
                echo json_encode($result);
            }

        }
    }
    /**
     *获取MySql版本信息
     */
    function getMysqlVersion(){
        $result = $GLOBALS['conn']->query("select VERSION() as VERSION");
        $result->execute();
        $result->setFetchMode(PDO::FETCH_ASSOC);
        if ($rows = $result->fetch()){
            return $rows['VERSION'];
        }
    }
    /**
     * 后台用户注销
     */
    function adminLogout()
    {
        unset($_SESSION["username"]);
        $result = array("msg" => "注销成功", "errorCode" => 0);
        echo json_encode($result);
    }
    /**
     * 后台用户修改密码
     * param：password（以前密码）
     * param：newpassword（新密码）
     */
    function modifypass($password,$newpassword){
        if (md5($password) == $_SESSION["userpwd"]){
            $stmt = $GLOBALS['conn']->prepare("update admin set userpwd=:userpwd where id=" . $_SESSION["userid"] );
            $stmt->bindParam("userpwd",md5($newpassword));
            $rs = $stmt->execute();
            if ($rs) {
                $result = array("msg" => "操作成功","errorCode"=>0);
                $_SESSION["userpwd"] = md5($newpassword);
            } else {
                $result = array("msg" => "操作失败","errorCode"=>1);
            }
            echo json_encode($result);
        }else{
            $result = array("msg" => "原始密码错误","errorCode"=>2);
            echo json_encode($result);
        }
    }
}

$user = new user();
$method = $_POST['method'];
if ($method == "getUserListByPage") {
    $pageIndex = $_POST['pageIndex'];
    $pageSize = $_POST['pageSize'];
    $username = $_POST['username'];
    $usersex = $_POST['usersex'];
    $usertel = $_POST['usertel'];
    $user->getUserListByPage($pageIndex,$pageSize, $username,$usersex,$usertel);
}
if ($method == "adminLogin") {
    $usertel = $_POST["usertel"];
    $userpwd = md5($_POST["userpwd"]);
    $verifyCode = $_POST["verifyCode"];
    $user->adminLogin($usertel, $userpwd, $verifyCode);
}
if ($method == "adminLogout") {
    $user->adminLogout();
}
if ($method == "modifypass") {
    $password = $_POST["password"];
    $newpassword = $_POST["newpassword"];
    $user->modifypass($password,$newpassword);
}
if ($method == "resetPassword") {
    $id= $_POST["id"];
    $user->resetPassword($id);
}
if ($method == "modifyStatus") {
    $id= $_POST["id"];
    $userstatus= $_POST["userstatus"];
    $user->modifyStatus($id,$userstatus);
}
?>